package cn.chencq.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.Key;
import java.util.Date;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

/**
 * 
 * Jwt 解析工具类
 * 
 * @author chencq
 * @email chenchaoqun@incar100.com
 * @date 2018-3-13 上午11:18:43
 */
public class JwtHelper {

	private static final String JWT_SECRET = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";

	public static Claims parseJWT(String token) {
		Claims claims = null;
		try {
			claims = Jwts
					.parser()
					.setSigningKey(
							DatatypeConverter.parseBase64Binary(JWT_SECRET))
					.parseClaimsJws(token.replace("Bearer ", "")).getBody();
		} catch (Exception ex) {
			claims = null;
		}
		return claims;
	}

	/**
	 * 
	 * 创建JWT token
	 * @Title: createJWT 
	 * @param map 
	 * @param expireTime token过期时间(毫秒)
	 * @return
	 * String
	 */
	public static String createJWT(Map<String, Object> map, long expireTime) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		// 生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter
				.parseBase64Binary(JWT_SECRET);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes,
				signatureAlgorithm.getJcaName());

		// 添加构成JWT的参数
		JwtBuilder builder = Jwts.builder()
				.setClaims(map)
				.signWith(signatureAlgorithm, signingKey);

		// 添加Token过期时间
		if (expireTime >= 0) {
			Date exp = new Date(expireTime);
			builder.setExpiration(exp)
				   .setNotBefore(new Date());
		}

		// 生成JWT
		return builder.compact();
	}
}
